<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Content extends CI_Controller {
	var $perpage = 20;

		public function __construct() {
		   parent::__construct();
		   if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) redirect('auth/login/'.str_replace("/", ".",$_SERVER['REQUEST_URI']));
		   $this->layout->setlayout('admin/layout');
		   $this->crumps->push('/admin/content/', 'Страницы');
		   $this->users_rights_model->check_rights(strtolower(get_class()), $this->router->get_method());
	   }

	public function index()	{
		$data['from'] = $from = $this->input->get('from', true);
		if ($from == "") $from = 0;
		$data['pages'] = $pages = $this->db->select()->from('content')->order_by('page_path', 'asc')->get()->result_array();
		$this->layout->view('admin/content/index', $data);
	}
	public function edit($id = 0) {
		$this->crumps->push('/admin/content/'.($id == 0?'add':'edit/'.$id).'/', ($id == 0?"Добавление":"Редактирование"));
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('content')->where('page_id', $id)->get()->row_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/content');

		$form = new jQuickForm('simple');

		$form->setLabel(($id == 0?"Добавление":"Редактирование").' страницы');

		$form->insertInputText('page_title')->setLabel('Название')->addRuleRequired();
		$form->insertInputText('page_desc')->setLabel('Текст для меню')->setComment('Только для корня');

		$tree = $this->content_model->getTree();
		$select = $form->insertSelect('page_parent')->setLabel('Родительская страница');
		$select->addOption('Корень сайта', 0);
		$cant_select = false;
		$this_segment = 1000;
		foreach ($tree as $t) {
			$attr = array();
			$seg = sizeof(explode("&", $t['page_path'])) - 1;
			$i = 0;
			$add_text = "";
			while($i < $seg) {
				$add_text .= "&nbsp;&nbsp;&nbsp;";
				$i++;
			}

			if ($id != 0) {
				if ($t['page_id'] == $id) {
					$attr['disabled'] = "disabled";
					$this_segment = $seg;
				}

				if ($seg > $this_segment) {
					$cant_select = true;
				}
				if ($seg == $this_segment && $t['page_id'] != $id) {
					$cant_select = false;
					$this_segment = 10000;
				}
				if ($cant_select) {
					$attr['disabled'] = "disabled";
				}
			}

			$option = $select->addOption($add_text."&rarr;&nbsp;".mb_substr($t['page_title'], 0, 30)." [".mb_substr($t['page_curl'], 0, 15)."]", $t['page_id'], $attr);

		}

		if ($id != 0 && $page['page_model'] != "" && $page['page_with_text'] == 0) {
			$form->insertStatic('Эта страница является модулем, т.е. отдельным разделом сайта. Чтобы редактировать содержимое раздела выберите соответствующий пукнт из левого меню.');
		} else {
			$form->insertFCKeditor('page_text')->setLabel('Текст страницы');
		}
		$form->insertInputText('page_pagetitle')->setLabel('Для тега title');
		$form->insertInputText('page_description')->setLabel('Для тега description');
		$form->insertInputText('page_keywords')->setLabel('Для тега keywords');
		if ($this->ion_auth->is_root()) {

			$curl = $form->insertInputText('page_curl')->setLabel('Адрес страницы')->setComment('ЧПУ - человеко понятный урл, <span style="color: black;">http://'.$_SERVER['HTTP_HOST'].'/<strong>[адрес страницы]</strong>/</span>');
			if ($page['page_curl'] == 'homepage') $curl->setAttribute('readonly', 'readonly');
			$gr = $form->insertGroup()->addClass('col col2');
			$select = $gr->insertSelect('page_with_text')->setLabel('Показывать текст вместе с модулем');
			$select->addOption('Да', 1);
			$select->addOption('Нет', 0);
			$select = $gr->insertSelect('page_crumps')->setLabel('Показывать в крошках');
			$select->addOption('Да', 1);
			$select->addOption('Нет', 0);

			$gr = $form->insertGroup()->addClass('col col2');
			$gr->insertInputText('page_model')->setLabel('Модель');
			$gr->insertInputText('page_function')->setLabel('Функция');
			$gr->insertInputText('page_active')->setLabel('При каких сегментах отмечать меню акивным')->setComment('Через запятую без пробела');
			$select = $gr->insertSelect('page_show_h1')->setLabel('Показывать h1 на странице');
			$select->addOption('Да', 1);
			$select->addOption('Нет', 0);


		} else {
			$form->addElement('hidden', 'page_curl')->setValue($page['page_curl']);
		}



		if ($_SERVER['REQUEST_METHOD'] == "POST" && $form->validate()) {
			if ($id == 0) {
				$p_data = $this->input->post();

				if ($p_data['page_curl'] == "") {
					$p_data['page_curl'] = $this->content_model->translate($p_data['page_title']);
				}

				$p_data['page_author'] = $this->ion_auth->get_user()->id;
				$p_data['page_creation'] = time();
				$p_data['page_status'] = 1;

				$this->db->insert('content', $p_data);
				$result = $this->db->insert_id();

				$this->content_model->updateAllPath();

				$this->session->set_flashdata('msg', 'Успешно добавлено');
				redirect('admin/content/edit/'.$result.'/');
			} else {
				$p_data = $this->input->post();
				if ($p_data['page_curl'] == "") {
					$p_data['page_curl'] = $this->content_model->translate($p_data['page_title']);
				}
				$this->db->update('content', $p_data, array('page_id'=>$id));
				$this->content_model->updateAllPath();
				$this->session->set_flashdata('msg', 'Успешно обновлено');
				redirect('admin/content/edit/'.$id.'/');
			}
		}
		$form->insertInputSubmit(($id == 0?"Добавить":"Сохранить"));

		$form->addDataSource(new HTML_QuickForm2_DataSource_Array($page));
		$data['form'] = $form."";
		$data['js'] = jQuickForm::js()->getJsAll();
		$this->layout->view('admin/content/edit', $data);
	}
	public function delete($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('content')->where('page_id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/content');
		$this->db->update('content', array('page_parent' => 0), array('page_parent' => $id));
		$this->db->delete('content', array('page_id' => $id));
		$this->content_model->updateAllPath();
		$this->session->set_flashdata('msg', 'Успешно удалено');
		redirect('admin/content/'.$pgng);
	}
	public function block($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('content')->where('page_id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/content');
		$this->db->update('content', array('page_status' => 0), array('page_id' => $id));
		$this->session->set_flashdata('msg', 'Успешно');
		redirect('admin/content/'.$pgng);
	}
	public function unblock($id = 0) {
		$from = $this->input->get('from', true);
		if ($from != "" && is_numeric($from)) $pgng = "?from=".$from;
		if ($id != 0) $data['page'] = $page = $this->db->select()->from('content')->where('page_id', $id)->get()->result_array();
		if ($id != 0 && sizeof($page) <= 0) redirect('admin/content');
		$this->db->update('content', array('page_status' => 1), array('page_id' => $id));
		$this->session->set_flashdata('msg', 'Успешно');
		redirect('admin/content/'.$pgng);
	}
	public function add() {
		return $this->edit(0);
	}
	public function ordering() {
		$post = $this->input->post();
		foreach ($post['order'] as $key => $val) {
			$this->db->where('page_id', $key)->update('content', array('page_order' => $val));
		}
		$this->content_model->updateAllPath();
		redirect('admin/content');
	}
}